# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'ks': {  # 汇付亚洲 银联快捷 2.3% 10-2000 dwc
        'API_KEY': 'Auq2&ZDsw#Y$brSxngMfcD*iRjQV&Caj',
        'gateway': 'https://api.flyhongyi.com:22891/pay/index.html',
        'query_gateway': 'https://api.flyhongyi.com:22891/query/v2',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


# $sign = md5($merid . $orderno . $paytype. $money. $notifyurl .$time . html_entity_decode($key));
def generate_sign(d, key):
    s = d['merid'] + d['orderno'] + d['paytype'] + d['money'] + d['notifyurl'] + d['time'] + key
    return _gen_sign(s)


# $sign=md5("{$merid}{$data['orderno']}{$data['money']}{$data['merorderno']}{$data['time']}{$key}");
def generate_notify_sign(d, key):
    s = d['merid'] + str(d['orderno']) + str(d['money']) + str(d['merorderno']) + str(d['time']) + key
    return _gen_sign(s)


def generate_query_sign(d, key):
    s = d['merid'] + d['orderno'] + d['time'] + key
    return _gen_sign(s)


def generate_query_rsp_sign(app_id, d, key):
    s = str(app_id) + str(d['orderno']) + str(d['money']) + str(d['merorderno']) + str(d['time']) + key
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("huifuyazhoupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def verify_query_rsp_sign(app_id, params, key):
    sign = params['sign']
    calculated_sign = generate_query_rsp_sign(app_id, params, key)
    if sign != calculated_sign:
        _LOGGER.info("huifuyazhoupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 支付类型:1.支付宝,2.微信,3.QQ,4.银联
def _get_pay_type(service):
    if service == 'wxpay':
        payType = '2'
    elif service == 'alipay':
        payType = '1'
    elif service == 'qq':
        payType = '3'
    elif service == 'unionpay':
        payType = '4'
    else:
        payType = '4l'
    return payType


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _get_device_id(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_id') or 'IMEI00000001111112222222'


def _get_device_type(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_type') or 'android'


def _get_device_tel(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('tel') or ''


def _get_user_name(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('user_name') or ''


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info['service']
    parameter_dict = OrderedDict((
        ('merid', app_id),
        ('orderno', str(pay.id)),
        ('paytype', _get_pay_type(service)),
        ('money', str(int(pay_amount * 100.0))),
        ('notifyurl', '{}/pay/api/{}/huifuyazhoupay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('deviceip', _get_device_ip(info)),
        ('deviceid', _get_device_id(info)),
        ('devicetype', '1'),
        ('payname', _get_device_tel(info)),
        ('payrealname', _get_user_name(info)),
        ('time', str(int(time.time()))),
        ('attach', 'charge'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("huifuyazhoupay create  data: %s", json.dumps(parameter_dict))
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("huifuyazhoupay create rsp data: %s", response.text)
    url = json.loads(response.text)['payurl'].replace('\/', '/').replace('HTTPS://QR.ALIPAY.COM/',
                                                                         'https://qr.alipay.com/')
    _LOGGER.info("huifuyazhoupay create url: %s", url)
    return {'charge_info': url}


# SUCCESS
def check_notify_sign(request, app_id):
    data = json.loads(request.body)
    api_key = _get_api_key(app_id)
    _LOGGER.info("huifuyazhoupay notify data: %s", request.body)
    data['merid'] = app_id
    verify_notify_sign(data, api_key)
    pay_id = data['merorderno']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('huifuyazhoupay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['status'])
    trade_no = data['orderno']
    total_fee = float(data['money']) / 100.0
    discount = float(json.loads(pay.extend or '{}').get('discount', 0))
    extend = {
        'discount': discount,
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    check_channel_order(pay_id, total_fee, app_id)
    # // 支付状态:1 - -表示支付成功
    if trade_status == '1':
        _LOGGER.info('huifuyazhoupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    pass
